package pers.vinsonws.jianghu.serverspring.controller;

import io.netty.channel.Channel;
import io.netty.channel.ChannelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pers.vinsonws.jianghu.codeCompont.MsgEveryPro;
import pers.vinsonws.jianghu.serverspring.channel.ChannelManager;
import pers.vinsonws.jianghu.serverspring.service.ChatRoomServiceImpl;
import pers.vinsonws.jianghu.serverspring.service.UserServiceImpl;
import pers.vinsonws.jianghu.serverspring.session.NetSession;
import pers.vinsonws.jianghu.tools.DivisMessage;
import pers.vinsonws.jianghu.tools.MergeMessage;
import pers.vinsonws.jianghu.util.User;

/**
 * @auther vinsonws
 * @date 2018/11/6 0:07
 * 主要控制注册和登录 //加一个更改用户资料
 */
@Component
public class SignCtrl {
    private static final Logger log = LoggerFactory.getLogger(SignCtrl.class);

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private ChatRoomServiceImpl chatRoomService;

    @Autowired
    private ChannelManager channelManager;//登录过后将channel存到ChannelManager//并在session中设置哦其为登录状态

    /**
     *
     * @param message
     * @return
     */
    public MsgEveryPro.Message toSignIn(MsgEveryPro.Message message, Channel channel, NetSession session){
        if (message.getType() != 2){
        throw new IllegalStateException("非法登录类型");
        }
        DivisMessage divisMessage = new DivisMessage(message.getMessage(), message.getType());
        User user = userService.loginByUidAndPassword(divisMessage.getStrByIndex(1),
                divisMessage.getStrByIndex(2));
        //存channel
        if (user == null) return null;
        if (channelManager.getChannelByUserId(user.getId()) != null){
            log.info("此用户已登录！");
            return null;
        }
        if (!channelManager.addChannel(user.getId(),  channel)) throw new ChannelException("存储channel失败");
        //session
        session.setOnline(true);
        session.setUser(user);
        if (user == null){
            throw new NullPointerException("未找到用户！");
        }
        /**
         * 发给所有在线的人，我上线了
         */
        {
            MsgEveryPro.Message.Builder builder = MsgEveryPro.Message.newBuilder();
            builder.setType(12);
            String[] ss = {String.valueOf(user.getId()),user.getUserName()};
            builder.setOnline(true);
            builder.setDateLong(System.currentTimeMillis());
            builder.setMessage(MergeMessage.infoToMessage(ss, 12));
            for (int i:channelManager.getAllOnlineUserId()){
                channelManager.getChannelByUserId(i).writeAndFlush(builder.build());
            }
        }


        MsgEveryPro.Message.Builder builder = MsgEveryPro.Message.newBuilder();
        builder.setType(message.getType());
        String[] ss = {String.valueOf(user.getId()),user.getUserName()};
        builder.setOnline(true);
        builder.setDateLong(System.currentTimeMillis());
        builder.setMessage(MergeMessage.infoToMessage(ss, message.getType()));

        return builder.build();
    }

    /**
     *
     * @param message
     * @return
     * @throws Exception
     */
    public String toSignUp(MsgEveryPro.Message message) throws Exception {
        if (message.getType() == 1) {
            DivisMessage divisMessage = new DivisMessage(message.getMessage(), message.getType());
            String s = userService.registerByUserNameAndPassword(divisMessage.getStrByIndex(1),
                    divisMessage.getStrByIndex(2));
            String[] ss = {s};
            return MergeMessage.infoToMessage(ss, message.getType());
        }else {
            throw new IllegalStateException("非法注册类型");
        }

    }

    public String updateUserInfo(MsgEveryPro.Message message, NetSession session){
        if (message.getType() != 5) throw new IllegalStateException("非法更改资料类型");
        DivisMessage divisMessage = new DivisMessage(message.getMessage(), message.getType());
        String messageSend = "";
        if (divisMessage.getLength() == 3){
            userService.updateUserInformation(session.getUser(),
                    divisMessage.getStrByIndex(1),
                    divisMessage.getStrByIndex(2),
                    divisMessage.getStrByIndex(3));
            String[] ss = {"1"};
            messageSend = MergeMessage.infoToMessage(ss, message.getType());
        }
        return messageSend;
    }

    public void loginOut(int id){
        channelManager.removeChannel(id);
        /**
         * 发给所有在线的人，我下线了
         */
        {
            User user = userService.getUserById(id);
            MsgEveryPro.Message.Builder builder = MsgEveryPro.Message.newBuilder();
            builder.setType(13);
            String[] ss = {String.valueOf(user.getId()),user.getUserName()};
            builder.setOnline(true);
            builder.setDateLong(System.currentTimeMillis());
            builder.setMessage(MergeMessage.infoToMessage(ss, 13));
            for (int i:channelManager.getAllOnlineUserId()){
                channelManager.getChannelByUserId(i).writeAndFlush(builder.build());
            }
        }
    }
}
